<template>
  <Modal
    v-model:visible="visible"
    :title="title"
    @ok="modalHandleOk"
    cancel-text="取消"
    ok-text="确认"
    :afterClose="afterClose"
  >
    <UploadDragger
      v-model:fileList="fileList"
      :before-upload="beforeUpload"
      :accept="accept"
      :maxCount="1"
      @remove="handleRemove"
      @change="handleChange"
      @drop="handleDrop"
    >
      <p class="ant-upload-drag-icon">
        <inbox-outlined></inbox-outlined>
      </p>
      <p class="ant-upload-text">单击或拖动文件到此区域进行上传</p>
    </UploadDragger>

    <a @click="DownloadTemp">下载模板</a>
  </Modal>
</template>
<script lang="ts" name="import">
  import { InboxOutlined } from '@ant-design/icons-vue';
  import type { UploadChangeParam } from 'ant-design-vue';

  import { defineComponent, ref } from 'vue';
  // import { defHttp } from "/@/utils/http/axios";
  import { defHttp as exportHttp } from '@/utils/http/axios/requestFile';

  import { message } from 'ant-design-vue';
  import type { UploadProps } from 'ant-design-vue';

  import { Modal, UploadDragger } from 'ant-design-vue';

  import { saveAs } from 'file-saver';
  import axios from 'axios';

  import { getToken } from '/@/utils/auth';

  export default defineComponent({
    props: {
      title: {
        type: String,
        default: '数据导入',
      },
      tempUrl: {
        type: String,
        default: '',
      },
      uploadUrl: {
        type: String,
        default: '',
      },
      uploadSuccess: {
        type: Function,
        default: null,
      },
      accept: {
        type: String,
        default: '',
      },
      hide: {
        type: Function,
        default: () => {},
      },
    },
    components: {
      InboxOutlined,
      Modal,
      UploadDragger,
    },
    emits: ['upload_success'],
    setup(props, { emit }) {
      const { tempUrl, uploadUrl, uploadSuccess, hide } = props;

      const visible = ref<boolean>(false);
      const fileList = ref<UploadProps['fileList']>([]);
      const uploading = ref<boolean>(false);

      const showModal = () => {
        visible.value = true;
      };

      const modalHandleOk = (e: MouseEvent) => {
        handleUpload()
          .then((res) => {
            visible.value = false;
            uploadSuccess(res);
          })
          .catch((res) => {
            fileList.value = [];
          });
      };

      const handleRemove: UploadProps['onRemove'] = (file) => {
        const index = fileList.value.indexOf(file);
        const newFileList = fileList.value.slice();
        newFileList.splice(index, 1);
        fileList.value = newFileList;
      };

      const beforeUpload: UploadProps['beforeUpload'] = (file) => {
        fileList.value = [...fileList.value, file];
        return false;
      };

      const handleChange = (info: UploadChangeParam) => {
        const status = info.file.status;
        if (status !== 'uploading') {
        }
        if (status === 'done') {
          // message.success(`${info.file.name} file uploaded successfully.`);
        } else if (status === 'error') {
          // message.error(`${info.file.name} file upload failed.`);
        }
      };
      const handleDrop = (e: DragEvent) => {
      };

      const handleUpload = () => {
        const formData = new FormData();

        if (!fileList.value || fileList.value.length == 0) {
          return;
        }
        var file = fileList.value[0].originFileObj;
        formData.append('file', file as any);

        // defHttp.uploadFile({ url: uploadUrl }, { file: file });

        // fileList.value.forEach((file: UploadProps['fileList'][number]) => {
        //     formData.append('file', file as any);
        // });

        let windowInstance: any = window;
        let baseUrl: string = windowInstance.config.base_url;

        const token = getToken();

        var http = axios.create({
          baseURL: baseUrl,
          headers: {
            'Content-Type': 'multipart/form-data',
            Authorization: token,
          },
        });

        return new Promise((resolve, reject) => {
          http
            .post(uploadUrl, formData)
            .then((response) => {
              message.success(response.data.msg || '导入成功');
              resolve(response.data);
            })
            .catch((error) => {
              message.error(error.response.data.msg);
              reject(error.response);
            });
        });

        // You can use any AJAX library you like
        // request('https://www.mocky.io/v2/5cc8019d300000980a055e76', {
        //     method: 'post',
        //     data: formData,
        // })
        //     .then(() => {
        //         fileList.value = [];
        //         uploading.value = false;
        //         message.success('upload successfully.');
        //     })
        //     .catch(() => {
        //         uploading.value = false;
        //         message.error('upload failed.');
        //     });
      };

      const DownloadTemp = () => {
        let res: any = exportHttp.get({ url: tempUrl });
        if (!res) return;
        let filename = decodeURIComponent(
          res.headers['content-disposition'].split('=')[2].split("''")[1],
        );
        saveAs(new Blob([res.data]), filename);
      };

      const afterClose = () => {
        hide && hide();
      };

      return {
        fileList,
        uploading,
        visible,
        handleRemove,
        beforeUpload,
        handleUpload,
        handleChange,
        handleDrop,

        showModal,
        modalHandleOk,

        DownloadTemp,

        afterClose,
      };
    },
  });
</script>
